package cn.felord.function.routes;


import cn.felord.function.entity.UserInfo;
import cn.felord.function.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;


/**
 * The type User controller.
 */
@Slf4j
@Component
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 等同于接口{@code @GetMapping("/user/{username})}.
     *
     * @return the router function
     */
    public RouterFunction<ServerResponse> getUserByName() {
        return RouterFunctions.route(RequestPredicates.GET("/get/{username}"),
                request -> ServerResponse.ok()
                        .body(userService.getByName(request.pathVariable("username"))));
    }


    /**
     * 从 request body 获取入参对象进行处理并将处理结果返回.
     *
     * @return the router function
     */
    public RouterFunction<ServerResponse> saveUser() {
        return RouterFunctions.route().POST("/save",
                request -> ServerResponse.ok().body(
                        // request 中获取 请求对象 保存
                        userService.saveUser(request.body(UserInfo.class))))
                .build();
    }

    /**
     * Del user router function.
     *
     * @return the router function
     */
    public RouterFunction<ServerResponse> delUser() {
        return RouterFunctions.route().POST("/del/{username}",
                request -> ServerResponse.ok().body(
                        userService.delUser(request.pathVariable("username")) ))
                .build();
    }

    /**
     * Update user router function.
     *
     * @return the router function-webmvc
     */
    public RouterFunction<ServerResponse> updateUser() {
        return RouterFunctions.route().POST("/update",
                request -> ServerResponse.ok().body(
                        // request 中获取 请求对象 新增
                        userService.updateUser(request.body(UserInfo.class))))
                .build();
    }

}
